<?php
namespace control;
class costAdjustmentClass extends adIndexClass
{
	private const page           = 'costAdjustment';
	private const table          = 'inventory_cost';
	private const tableMx        = 'inventory_cost_detail';
	private const tableRecord    = 'inventory_record';
	private const tableinv       = 'inventory';
	private const tableinvDetail = 'inventory_detail';
	private const title          = '成本调整单';
	private const state          = ['草稿', '待确认', '已确认'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '{l.costAdjustment.homeSearch.orderNo}',
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'type' => [
                        'name'  => '{l.costAdjustment.homeSearch.type}',
                        'width' => 300,
                    ],
                    'money'  => [
                        'name'  => '{l.costAdjustment.homeSearch.money}（' . static::$unit . '）',
                        'width' => 300,
                    ],
                    'orderDate'  => [
                        'name'  => '{l.costAdjustment.homeSearch.orderDate}',
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'state'  => [
                        'name'  => '{l.costAdjustment.homeSearch.state}',
                        'width' => 300,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('costAdjustment.home.orderNo') => text(array("name" => "orderNo")),
                    L('costAdjustment.homeSearch.orderDate')   => text(['name' => 'orderDate', 'laydate' => ['range' => '~', 'type' => 'date']]),
                    L('costAdjustment.home.state') => select(["name" => "state", 'option' => self::state]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/*列表-查询条件*/
	public function home()
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . L('costAdjustment.homeSearch.detail') . "','" . $url . "&fun=edit')\" class='spanButton'>".L('costAdjustment.homeSearch.new')."</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">".L('costAdjustment.homeSearch.del')."</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/*客户列表-查询结果*/
	public function homeSearch()
	{
		//查询结果
		$where = " coid = '" . self::$coid . "' ";
		$equal = [
			'state' => $this->post('state'),
		];
		$like  = [
			'orderNo' => $this->post('orderNo'),
		];
		//生成查询语句
		$where .= search([
			"="    => $equal,
			"like" => $like,
		]);
		if ($this->post('orderDate')) {
			$where .= self::timeComparison($this->post('orderDate'), 'date', 'orderDate');
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		$page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = array(
				"box"    => ["name" => "listId", "value" => $array['id']],
				"detail" => [
					"title" => L('costAdjustment.homeSearch.detail'),
					"click" => "newIframe('" . L('costAdjustment.homeSearch.detail') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')",
				],
				"edit"   => ($array['state'] != '已确认') ? [
					"title" => L('costAdjustment.homeSearch.edit'),
					"click" => "newIframe('" . L('costAdjustment.homeSearch.detail') . "','" . $url . "&fun=edit&id=" . $array['id'] . "')",
				] : [],
			);
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'money':
                        $money    = find(array('table' => self::tableMx, 'where' => "orderId = '$array[id]'", 'sum' => "price"));
                        $row[] = $money;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
        $totalQuery = find([
            'table'  => self::tableMx,
            'single' => "orderId in (select id from ".self::table." where {$where})",
            'field'  => "ifnull(sum(price),0) as price",
        ]);
        $total    = [
            'money'        => self::lostZero($totalQuery['price']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
		//返回
		$json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}

    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }
	/**
	 * 编辑页
	 *
	 * @return string
	 */
	public function edit(): string
	{
		$id   = $this->get('id');
		$info = query(self::table, " coid = '" . self::$coid . "' AND id = '" . $id . "' ");

		$button[] = [
			'style' => 'li-btn-blue-bg',
			"name"  => L('costAdjustment.edit.save'),
			"type"  => "点击事件",
			"title" => L('costAdjustment.edit.save'),
			'fun'   => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
		];
        $button[] = [
            "name" => "保存并提交",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=saveAndCommit')"
        ];
		$tr[]     = ['', '{l.costAdjustment.edit.code}', '{l.costAdjustment.edit.name}', '{l.costAdjustment.edit.model}', '{l.costAdjustment.edit.unit}', '<div style="position: relative" class="warehouse">' . '{l.costAdjustment.edit.warehouse}' . inStockOtherClass::chooseWarehouse() . '</div>', '{l.costAdjustment.edit.inventoryNum}', '{l.costAdjustment.edit.inventoryMoney}（' . static::$unit . '）', '调整后金额（' . static::$unit . '）', '{l.costAdjustment.edit.remark}'];
		$result   = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by time"));
        $totalArr = ['price'=>0];
		foreach ((array)$result['array'] as $k=>$array) {
			$material    = query('material', " id = '$array[materialId]'");
			$tr[]        =
				[
                    componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
					hidden(['name' => 'mxId[]', 'value' => $array['id']]) .
					hidden(['name' => 'materialId[]', 'value' => $array['materialId'],]),
					$material['code'],
					$material['name'],
					$material['model'],
                    $array['unit'].hidden(['name' => 'unit[]', 'value' => $array['unit']]),
					idSelect([
					    'name' => 'warehouseId[]',
                        'sqlForm' => "warehouse WHERE state = '启用' ",
                        'change' => 'getInventory',
                        'sqlId' => 'id',
                        'sqlField' => "name",
                        'title' => '仓库',
                        'value' => $array['warehouseId']
                    ]),
                    "<span class='inventory'>".self::lostZero($array['orderNum'],'numPrecision')."</span>",
                    "<span class='inventoryMoney'>".self::lostZero($array['orderPrice'],'pricePrecision')."</span>",
					text(['name' => 'price[]', 'blur' => 'calculateTotal', 'value' => self::lostZero($array['price'],'pricePrecision')]),
					text(['name' => 'mxText[]', 'value' => $array['text']]),
				];
            $totalArr['price'] += $array['price'];
		}
        $total = [
            8 => "<span id='total_price'>".self::lostZero($totalArr['price'],'numPrecision')."</span>",
        ];
        $table  = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total));
		$page  = self::page;
		$choiceMaterialWord = L('costAdjustment.edit.choiceMaterial');
        $but = <<<EOT
                <span class="smallButton" onclick="layer('{$this->get('cla')}','addMx', $('form[name={$page}EditForm]').serialize())">$choiceMaterialWord</span>
EOT;

		//表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . L('costAdjustment.edit.type') => select(['name' => "type", 'class' => 'text', 'value' => $info['type'], 'option' => explode('，', para('costAdjustmentType')),]),
                    must . L('costAdjustment.edit.orderDate') => text(
                        ['name' => "orderDate", 'class' => 'text', 'value' => $info['orderDate'] ?: $this->date, 'laydate' => [],]
                    ),
                ],
                [
                    L('costAdjustment.edit.remark')          => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => L('costAdjustment.edit.adjustmentMx'),
            'button' => $but,
            'html' => $table,
        ]);
		$data['html'] = $this->pageEdit([
			"html"  => $body,
			'hidden' => hidden(['name' => 'id', 'value' => $id]),
		]);
		$data['html'] .= <<<EOT
<script>
function addRow(){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
        $("#materialTable tbody").append(res.html);
        resetNumber($("#materialTable"))
    },'json');
}

function assign(e) {
    let val = $(e).find("option:selected").text()
    let name = $(e).attr('name').replace('Id', '')
    $("[name="+name+"]").val(val);
}
//获取当前可用库存
function getInventory(e){
    let warehouseId = e.value;
    let materialId = $(e).parent().parent().find("[name='materialId[]']").val();
    let unit = $(e).parent().parent().find("[name='unitDetail[]']").val();
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getInventory',{warehouseId:warehouseId,materialId:materialId,unit:unit},function(res) {
          $(e).parent().parent().find(".inventory").html(res.num);
          $(e).parent().parent().find(".inventoryMoney").html(res.money);
    },'json');
}
$(".warehouse .stateBlock li").on('click',function() {
    let id = $(this).data('id');
     $("select[name='warehouseId[]']").each(function() {
      let obj = $(this);
      obj.val(id);
      getInventory(this);
    });
   $(".stateBlock").hide();
})
//计算总数量
function calculateTotal(){
    let table = $('.editList')
    let price = 0
    table.find("[name='price[]']").each(function(index){
        if($(this).val()){
          price+=Number($(this).val());
        }
    })
    $("#total_price").text(price.toFixed(amountPrecision));
}
</script>

EOT;
		//返回
		return $this->tab($data);
	}
    /**
     * 获取当前可用库存
     */
    public function getInventory(): bool|string
    {
        $warehouseId   = $this->post('warehouseId');
        $materialId = $this->post('materialId');
        //当前可用库存(已包含占用库存)
        $inventoryNum   = inventoryBalanceClass::inventoryNum($materialId,$warehouseId);
        $json['num']  = $inventoryNum;
        $inventoryPrice = inventoryBalanceClass::unitPrice($materialId);
        $json['money'] = round($inventoryPrice * $inventoryNum,2);
        return json_encode($json, 320);
    }

	public function editEdit()
	{
		$id               = $this->post('id') ?: self::getId();
		$mxIdArr          = $this->post('mxId') ?: [];
		$materialIdArr = $this->post('materialId');
		$warehouseIdArr   = $this->post('warehouseId');
		$unitArr          = $this->post('unit');
		$priceArr         = $this->post('price');
        $mxTextArr        = $this->post('mxText');
		$field            = [
			'type'      => $this->post('type'),
			'orderDate' => $this->post('orderDate'),
			'text'      => $this->post('text'),
		];
		$annotation       = [
			'type'      => L('costAdjustment.editEdit.type'),
			'orderDate' => L('costAdjustment.editEdit.orderDate'),
			'text'      => L('costAdjustment.editEdit.text'),
		];
		$rules            = [
			'type'      => 'required',
			'orderDate' => 'required',
			// 'text'           => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
			goto resp;
		}
		$where = " coid = '" . self::$coid . "' AND id = '$id' ";
		$info  = query(self::table, $where);
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = L('costAdjustment.editEdit.power');
		} elseif (static::is_null_array($mxIdArr)) {
			$json['warn'] = L('costAdjustment.editEdit.choiceMx');
		} elseif (static::is_null_array($materialIdArr)) {
			$json['warn'] = L('costAdjustment.editEdit.choiceMx');
		} elseif (static::is_null_array($priceArr)) {
			$json['warn'] = L('costAdjustment.editEdit.incompleteMoney');
		}elseif (static::is_null_array($unitArr)) {
			$json['warn'] = L('costAdjustment.editEdit.choiceUnit');
		} elseif (!empty($info['id']) && $info['state'] == '已确认') {
			$json['warn'] = L('costAdjustment.editEdit.stateError');
		} else {
			$this->startTrans();
			$isPass = true;//事务通过标志
			if (!$info['id']) {
				$orderNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'PD' . date('Ymd'),
                    'table'  => self::table,
                    'field'  => 'orderNo',
                    'where'  => " AND coid = '" . self::$coid . "' ",
                ],$field);

				$field        = array_merge($field, [
					'id'      => $id,
					'orderNo' => $orderNo,
					'state'   => '草稿',
					'coid'    => self::$coid,
					'stid'    => $this->control['stid'],
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field,]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}
			//添加或更新报价单明细
			if (is_array($mxIdArr)) {
				foreach ($mxIdArr as $k => $nid) {
					$mx          = query(self::tableMx, "id = '$nid'");
					$material    = query('material', "id = '$materialIdArr[$k]'");
                    $priceArr[$k] = self::formattingFigure($priceArr[$k],'pricePrecision');
                    $inventoryNum   = inventoryBalanceClass::inventoryNum($material['id'],$warehouseIdArr[$k]);
                    $inventoryPrice = inventoryBalanceClass::unitPrice($material['id']);
					// 跳过库存为0 金额为0
					if ($inventoryNum == 0 && round($inventoryNum*$inventoryPrice,2) == 0) {
						$json['warn'] = str_replace(['{{name}}','{{code}}','{{model}}',], [$material['name'],$material['code'],$material['model']], L('costAdjustment.editEdit.zero'));
						goto resp;
					}
					if (!empty($mx['id'])) {
						//更新
						$warn = static::update([
							"table" => self::tableMx,
							"field" => [
								'materialId'    => $materialIdArr[$k],
								'warehouseId'   => $warehouseIdArr[$k],
								'price'         => $priceArr[$k],
								'unit'          => $unitArr[$k],
								'orderPrice'    => round($inventoryNum*$inventoryPrice,2),
								'orderNum'      => self::formattingFigure($inventoryNum,'numPrecision'),
								'text'          => $mxTextArr[$k],
							],
							"where" => " id = '$nid'",
						]);
					} else {
						//新增
						$warn = static::insert([
							"table" => self::tableMx,
							"field" => [
								'id'            => $nid,
								'orderId'       => $id,
                                'materialId'    => $materialIdArr[$k],
								'warehouseId'   => $warehouseIdArr[$k],
								'price'         => $priceArr[$k],
                                'orderPrice'    => round($inventoryNum*$inventoryPrice,2),
                                'orderNum'      => self::formattingFigure($inventoryNum,'numPrecision'),
								'unit'          => $unitArr[$k],
								'text'          => $mxTextArr[$k],
							],
						]);
					}
					if (!in_array($warn, ['新增成功', '更新成功'])) {
						$isPass       = false;
						$json['warn'] = $warn;
						break;
					}
				}
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
				$this->commitTrans();
				delete(['table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"]);
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = str_replace(['{{staffName}}','{{type}}','{{id}}',], [$this->control['name'],$type,$id], L('costAdjustment.editEdit.log'));
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
			} else {
				$this->rollback();
			}
		}

		resp:
		return json_encode($json, 320);
	}


	/**
	 * @return bool|string
	 */
	public function addMx()
	{
        $materialClassObj = new materialClass();
        $layerId          = $this->get('cla') . ucwords($this->get('fun'));
        $formName         = 'mxForm';
        $notAllowRepeat   = 1;
        $callback = $this->post('callback') ? $this->post('callback') : self::page;
        $tableMx  = $this->post('tableMx');
        $data             = [
            'sub'            => " onclick=\"addRow();$('#" . $layerId . "').remove()\" ",
            'continueAdding' => $notAllowRepeat ? " onclick=\"addRow();removeSelectedContent('" . $formName . "')\" " : " onclick=\"addRow();\" ",
            'hidden'         => hidden(["name" => "tableMx", 'value' => $tableMx])
                . hidden(['name' => 'orderId', 'value' => $this->post('orderId')]) .
                hidden(array('name' => 'materialId', 'value' => $this->post('materialId') ? implode(',', $this->post('materialId')) : '')),
        ];
        return $materialClassObj->addMx($data);
	}

	/**
	 * 编辑
	 *
	 * @return bool|string
	 */
	public function addMxEdit()
	{
		$mxIdArr = $this->post('mxId');
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = L('costAdjustment.addMxEdit.power');
		} elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
			$json['warn'] = L('costAdjustment.addMxEdit.choice');
		} else {
			$json['html'] = '';
			$tr = [];
			foreach ($mxIdArr as $mxId) {
				$material       = query('material', "id = '$mxId'");
				$id             = self::getId();
				$inventoryNum   = inventoryBalanceClass::inventoryNum($material['id']);
				$inventoryPrice = inventoryBalanceClass::unitPrice($material['id']);
				//$select         = select(['name' => 'unit[]', 'option' => inventoryBalanceClass::materialUnit($material['materialId'])]);
				$select         = $material['unit'].hidden(['name' => 'unit[]', 'value' => $material['unit']]);
				$warehouseSel   = idSelect(array(
				    'name' => 'warehouseId[]',
                    'change' => 'getInventory',
                    'sqlForm' => "warehouse WHERE coid = '" . self::$coid . "' AND state = '启用' ",
                    'sqlId' => 'id',
                    'sqlField' => "name",
                    'title' => '仓库'
                ));
				$orderPrice     =  round($inventoryPrice * $inventoryNum,2);
                $inventoryNum = self::lostZero($inventoryNum,'numPrecision');
                $tr[] = [
                    componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $id)) .
                    hidden(array('name' => 'materialId[]', 'value' => $mxId)),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $select,
                    $warehouseSel,
                    "<span class='inventory'>$inventoryNum</span>",
                    "<span class='inventoryMoney'>$orderPrice</span>",
                    text(['name' => 'price[]', 'blur' => 'calculateTotal']),
                    text(['name' => 'mxText[]']),
                ];
			}
			$json['html'] = $this->tableMany(['tr'=>$tr,'thead'=>false]);
			$json['warn'] = 2;
		}
		return json_encode($json, 320);
	}


	/*详情页*/
	public function detail(): string
	{
		$info = query(self::table, " coid = '" . self::$coid . "' AND id = '{$this->get('id')}'");
		if (empty($info['id'])) {
			$html = L('costAdjustment.detail.empty');
		} else {
			//菜单
			$data   = array(
				"id" => $info['id'],
			);
			$button = [];
			if ($this->power(self::page, "edit") && $info['state'] != '已确认') {
				if ($info['state'] == '草稿') {
					//按钮
					$button[] = [
						"name"  => L('costAdjustment.detail.edit'),
						"type"  => "顶部页卡",
						"title" => L('costAdjustment.detail.editDetail'),
						"url"   => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
						'style' => 'li-btn-blue-bg',
					];
					//按钮
					$button[] = [
						"name" => L('costAdjustment.detail.sub'),
						"type" => "弹出层",
						"cla"  => $this->get('cla'),
						"fun"  => "operate",
						"post" => ["act" => 'commit', "id" => $info['id']],
					];
				}
				//按钮
				$button[] = [
					"name" => L('costAdjustment.detail.del'),
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'del', "id" => $info['id']],
				];
			}
			if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
				$button[] = [
					"name"  => L('costAdjustment.detail.sure'),
					"type"  => "弹出层",
					"cla"   => $this->get('cla'),
					"fun"   => "operate",
					"post"  => ["act" => 'confirm', "id" => $info['id']],
					'style' => 'li-btn-blue-bg',
				];
			}
			if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
				$button[] = [
					"name" => L('costAdjustment.detail.cancel'),
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'cancel', "id" => $info['id']],
				];
			}
            //操作记录
            $button[] = self::operateLogBut($info['id']);

			$mxtr[] = [L('costAdjustment.detail.code'), L('costAdjustment.detail.name'), L('costAdjustment.detail.model'), L('costAdjustment.detail.unit'), L('costAdjustment.detail.warehouse'), L('costAdjustment.detail.inventoryNum'), L('costAdjustment.detail.inventoryMoney').'（' . static::$unit . '）', '调整后金额（' . static::$unit . '）', L('costAdjustment.detail.remark')];
			$result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by time"));
			foreach ($result['array'] as $array) {
				$material    = query('material', " id = '$array[materialId]'");
				$mxtr[]      = [$material['code'], $material['name'], $material['model'],$material['unit'], warehouseClass::getName($array['warehouseId']), self::lostZero($array['orderNum'],'numPrecision'), self::lostZero($array['orderPrice'],'pricePrecision'), self::lostZero($array['price'],'pricePrecision'), $array['text'],];
			}
			$res = find(
				array(
					'table'  => self::tableMx,
					'field'  => "sum(price) as total",
					'single' => "orderId = '$info[id]' group by orderId",
				)
			);
            $total_tr = [
                    7=>self::lostZero($res['total'])
                ];
			//生成表单
            $data['button'] = $this->tableShowButton($button);
			$data['html'] = $this->tableShow([
				'详细信息' => [
					[
                        L('costAdjustment.detail.type') => $info['type'],
                        L('costAdjustment.detail.orderDate') => $info['orderDate'],
                        L('costAdjustment.detail.orderNo') => $info['orderNo'],
                        L('costAdjustment.detail.stid')  => self::findStaff($info['stid']),
					],
					[
                        L('costAdjustment.detail.state')   => $info['state'],
					],
                    [
                        L('costAdjustment.detail.remark')   => pre($info['text']),
					],
				],
			]);
            $data['html'] .= $this->detailList([
                'title' => L('costAdjustment.detail.adjustmentMx'),
                'html' => $this->listTable(array('tr' => $mxtr, 'showEmpty' => true, 'total' => $total_tr, 'showSort' => true)),
            ]);
            $data['html'] .= $this->detailBlock([
                '附件' => fileUploadClass::showFile($info['id'], '采购单')
            ]);
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

	/**
	 * 确认
	 */
	public function confirmEdit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
		$field = [
			'state'       => '已确认',
			'confirmTime' => $this->time,
		];
		if (!$this->power(self::page, 'confirm')) {
			$json['warn'] = L('costAdjustment.confirmEdit.power');
		} elseif (empty($info['id'])) {
			$json['warn'] = L('costAdjustment.confirmEdit.empty');
		} elseif ($info['state'] != '待确认') {
			$json['warn'] = L('costAdjustment.confirmEdit.stateError');
		} else {
			$this->startTrans();
			$isPass       = true; // 事务通过标志
			$json['warn'] = update([
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			]);
			if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass === true) {
				$details = find([
					'table' => self::tableMx,
					'where' => " orderId = '{$info['id']}'",
				]);
				$orderId = self::getId();
				$field   = [
					'orderDate'   => $this->date,
					'text'        => '成本调整单：' . $info['id'],
					'id'          => $orderId,
					'type'        => '成本调整',
					'classify'    => 1,
					'sourceTable' => self::table,
					'sourceId'    => $info['id'],
					'warehouseId' => '0000',
					'state'       => '已确认',
					'coid'        => self::$coid,
					'stid'        => $this->control['stid'],
				];
                $orderNo = codeTemplateClass::generateCode('inStockOther',[
                    'prefix' => 'CB' . date('Ymd'),
                    'table'  => self::table,
                    'field'  => 'orderNo',
                    'where'  => " AND coid = '" . self::$coid . "' ",
                ],$field);
                $field['orderNo'] = $orderNo;
				static::insert(["table" => self::tableinv, "field" => $field,]);
				foreach ($details['array'] as $value) {
					// 入库数量
					$inNum        = static::total([
						'sql'   => "SELECT IFNULL(SUM(d.num), 0) as total FROM `inventory_detail` as d, inventory as i WHERE d.orderId = i.id ",
						'where' => [
							'd.materialId' => $value['materialId'],
							'i.classify'      => 1,
							'd.coid'          => self::$coid,
						],
					]);
					$inventoryNum = inventoryBalanceClass::inventoryNum($value['materialId']);
					// 比例 = 库存数量 / 入库数量
					static::insert([
						'table' => self::tableinvDetail,
						'field' => [
							'id'            => self::getId(),
							'coid'          => self::$coid,
							'warehouseId'   => $value['warehouseId'],
							'materialId'    => $value['materialId'],
							'num'           => 0,
							'orderNum'      => 0,
							'money'         => $value['price'] / ($inventoryNum / $inNum),
							'sourceTable'   => self::tableMx,
							'sourceId'      => $value['id'],
							'unit'          => inventoryBalanceClass::materialUnit($value['materialId'])[0],
							'text'          => '成本调整单',
							'orderId'       => $orderId,
						],
					]);
                    //插入物料平均单价
                    $total = inventoryBalanceClass::inventoryNum($value['materialId']); //库存数量
                    $inventory_price = query(
                        "inventory_price",
                        " coid = '".self::$coid."' and materialId = '".$value['materialId']."' order by id desc ",
                        'avgPrice'
                    );
                    $oldAvgPrice = empty($inventory_price['avgPrice'])?0:(float)$inventory_price['avgPrice'];
                    $avgPrice = round(($oldAvgPrice*$total+$value['price'])/($total),4);
                    $field = [
                        'coid' => self::$coid,
                        'materialId' => $value['materialId'],
                        'avgPrice' => $avgPrice,
                        'recordTime'=>date('Y-m-d H:i:s'),
                        'time' => date("Y-m-d H:i:s"),
                    ];
                    static::insert(["table" => 'inventory_price', "field" => $field]);
				}
				$this->commitTrans();//提交事务
				auditingFollow(array(
					"type"   => "调整单",
					"typeId" => $info['id'],
					"text"   => "【{$this->control['name']}】确认",
				));
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = str_replace(['{{staffName}}','{{type}}','{{id}}'], [$this->control['name'],$type,$id], L('costAdjustment.confirmEdit.log'));
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
			}
		}
		resp:
		return json_encode($json, 320);
	}

	/**
	 * 取消
	 */
	public function cancelEdit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
		$field = [
			'state'       => '草稿',
			'checkId'     => '',
			'confirmTime' => '',
		];
		if (!$this->power(self::page, 'cancel')) {
			$json['warn'] = L('costAdjustment.cancelEdit.power');
		} elseif (empty($info['id'])) {
			$json['warn'] = L('costAdjustment.cancelEdit.empty');
		} else {
			$json['warn'] = update([
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			]);
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				auditingFollow(array(
					"type"   => "调整单",
					"typeId" => $info['id'],
					"text"   => "【{$this->control['name']}】取消",
				));
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = str_replace(['{{staffName}}','{{type}}','{{id}}'], [$this->control['name'],$type,$id], L('costAdjustment.cancelEdit.log'));
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
			}
		}
		resp:
		return json_encode($json, 320);
	}

	/**
	 * 提交
	 */
	public function commitEdit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
		$field = [
			'state' => '待确认',
		];
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = L('costAdjustment.commitEdit.power');
		} elseif (empty($info['id'])) {
			$json['warn'] = L('costAdjustment.commitEdit.empty');
		} elseif ($info['state'] != '草稿') {
			$json['warn'] = L('costAdjustment.commitEdit.stateError');
		} else {
			$json['warn'] = update(array(
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			));
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				auditingFollow([
					"type"   => "调整单",
					"typeId" => $info['id'],
					"text"   => "【{$this->control['name']}】提交",
				]);
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = str_replace(['{{staffName}}','{{type}}','{{id}}'], [$this->control['name'],$type,$id], L('costAdjustment.commitEdit.log'));
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get(
						'cla'
					) . "&fun=detail&id=" . $info['id'];
			}
		}
		resp:
		return json_encode($json, 320);
	}

	// 操作中转
	public function operate()
	{
		$act  = $this->post('act') ?? '';
		$pwd  = $word = false; // 需要密码
		$form = $power = '';
		switch ($act) {
			case 'confirm':
				$act      = 'confirm';
				$msg      = L('costAdjustment.operate.confirm');
				$title    = L('costAdjustment.operate.confirmTitle');
				$function = 'confirmEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$power    = '';
				$word     = true;
				break;
			case 'commit':
				$act      = 'edit';
				$msg      = L('costAdjustment.operate.commit');
				$title    = L('costAdjustment.operate.commitTitle');
				$function = 'commitEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$word     = true;
				break;
			case 'cancel':
				$act      = 'cancel';
				$msg      = L('costAdjustment.operate.cancel');
				$title    = L('costAdjustment.operate.cancelTitle');
				$function = 'cancelEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$word     = true;
				break;
			default:
				$act      = 'del';
				$msg      = L('costAdjustment.operate.del');
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm, quoForm';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('costAdjustment.operate.warn'));
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
				'word'     => $word,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 删除
	 *
	 * @return bool|string
	 */
	public function delete()
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = L('costAdjustment.delete.power');
		} elseif (empty($array)) {
			$json['warn'] = L('costAdjustment.delete.noChoice');
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id' ");
				if ($info['state'] == '已确认') {
					$warn = L('costAdjustment.delete.fail');
				} else {
					//最后删除基本参数
					delete(array("table" => self::table, "where" => " id = '$id' "));
					delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
					delete(array("table" => 'auditing_follow', "where" => " typeId = '$id' "));
					//返回
					$warn = L('costAdjustment.delete.success');
					$x++;
				}
				$text .= str_replace(['{{id}}'], [$info['id']], L('costAdjustment.delete.text')) . $warn . "。<br>";
			}
			//添加日志
			$text = str_replace(['{{staffName}}'], [$this->control['name']], L('costAdjustment.delete.log')). "<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('costAdjustment.delete.warn'));
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		return json_encode($json, 320);
	}
}
